package com.jf.blog.util;

import com.jf.blog.bean.Userinfo;
import com.jf.blog.service.UserinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class LoginUtil {
    private static StringRedisTemplate redisTemplate;
    private static UserinfoService userinfoService;
    private static HttpServletRequest request;

    @Autowired
    private LoginUtil(StringRedisTemplate redisTemplate, UserinfoService userinfoService, HttpServletRequest request) {
        LoginUtil.redisTemplate = redisTemplate;
        LoginUtil.userinfoService = userinfoService;
        LoginUtil.request = request;
    }

    public static Userinfo getLoginUser() {
        String token = request.getHeader(MyConstants.TOKEN);
        int userinfoId;
        if (token == null) {
            userinfoId = MyConstants.SUPER_ADMIN;
        } else {
            String value = redisTemplate.opsForValue().get(MyConstants.TOKEN_KEY + token);
            if (value == null) {
                userinfoId = MyConstants.SUPER_ADMIN;
            } else {
                userinfoId = Integer.parseInt(value);
            }
        }
        return userinfoService.getById(userinfoId);
    }

    public static void logout() {
        String token = request.getHeader(MyConstants.TOKEN);
        if (token != null) {
            redisTemplate.delete(token);
        }
    }
}
